package com.gjszn.kh.mail;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.mail.internet.MimeMessage;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

public class MailSender extends JavaMailSenderImpl implements JavaMailSender {
	private static Logger log = LogManager.getLogger(MailSender.class);
	
	private int single_account_max;
	// Accounts
	private ArrayList<String> userNameList;
	private ArrayList<String> passwordList;
	private int currentMailId = 0;
	
	@Override
	public void setJavaMailProperties(Properties javaMailProperties) {
		// TODO Auto-generated method stub
		super.setJavaMailProperties(javaMailProperties);
	}

	@Override
	public void setHost(String host) {
		// TODO Auto-generated method stub
		super.setHost(host);
	}

	private Map<String, Integer> accountMaxMap = new HashMap<String, Integer>();
	private int _single_account_max;
	@Override
	protected void doSend(MimeMessage[] mimeMessage, Object[] object) throws MailException {
		super.doSend(mimeMessage, object);
		if((_single_account_max--) <= 0){
			log.info("更换下一个邮箱账号-----------------------------");
			currentMailId = (currentMailId + 1) % userNameList.size();
			// Next Accounts
			super.setUsername(userNameList.get(currentMailId));
			super.setPassword(passwordList.get(currentMailId));
			_single_account_max = single_account_max;
		}
	}

	public int getSingle_account_max() {
		return single_account_max;
	}

	public void setSingle_account_max(int single_account_max) {
		this.single_account_max = single_account_max;
		this._single_account_max = single_account_max;
	}

	@Override
	public void setUsername(String username) {
		if (userNameList == null)
			userNameList = new ArrayList<String>();
		// split usernmae in ,
		String[] userNames = username.split(",");
		if (userNames != null) {
			for (String user : userNames) {
				userNameList.add(user.trim());
				accountMaxMap.put(user.trim(), single_account_max);
			}
		}
		// before send super.setXxx() // accounts
		super.setUsername(userNameList.get(currentMailId));
	}

	@Override
	public void setPassword(String password) {
		if (passwordList == null)
			passwordList = new ArrayList<String>();
		// split password in ,
		String[] passwords = password.split(",");
		if (passwords != null) {
			for (String pw : passwords) {
				passwordList.add(pw.trim());
			}
		}
		// before send super.setXxx() // accounts
		super.setPassword(passwordList.get(currentMailId));
	}
	 
}